#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Flask,request
import json
app = Flask(__name__)
from facility.cmd_fn import execute,execute_for_result
from facility import  Reader

script_path = 'static/scripts/'


@app.route('/', methods=['GET'])
def test():
    return '200'



############################################################
#  Scripts
############################################################
@app.route('/add_script', methods=['POST'])
def add_script():
    try:
        data = json.loads(request.get_data())
        assert data['name'] != ''
        open(script_path+data['name'],'w').write(data['data'])
    except: return  'fail'

    reader = Reader.load(script_path+'list.json')
    items = reader()
    items.append({'name':data['name'],'remark':data["remark"]})
    reader.save(items)
    return 'ok'


@app.route('/del_script/<name>', methods=['GET'])
def del_script(name):
    reader = Reader.load(script_path+'list.json')
    items = reader()
    items = [i for i in items if i['name'] != name]
    return  json.dumps(items)


@app.route('/run/<name>', methods=['GET'])
def run(name):
    execute('sh static/scripts/{}'.format(name))
    return name+'1231'


@app.route('/sync', methods=['GET'])
def sync():
    return '123321'


@app.route('/process_list', methods=['GET'])
def process_list():
    arr = execute_for_result('sh static/scripts/process_user.sh').strip().split('\n')
    return     json.dumps({"bizData":[[j for j in item.strip().split(' ') if j !=''] for idx,item in enumerate(arr) if idx !=0]})





if __name__ == '__main__':
    import sys
    try:
        # app.run(threaded=True, debug=True, use_reloader=False)
        app.run(threaded=True, debug=True, use_reloader=True,port=10001)
    except Exception as e:
        print(e)
        sys.exit(0)
